﻿using System;
using System.Web.Mvc;
using SuCasa.DataAccess;
using SuCasa.Infrastructure;
using SuCasa.Models;

namespace SuCasa.Controllers {
    public class CallLogController : Controller {
         readonly IMemberRepository _memberRepository;
         readonly ICallLogRepository _callLogRepository;
         public CallLogController()
         {
             if (Constants.UseFakes){
                 _memberRepository = new FakeMemberRepository();
                 _callLogRepository = new FakeCallLogRepository();
             }
             else{
                 _memberRepository = new MemberRepository(SuCasaContext.Instance);
                 _callLogRepository = new CallLogRepository(SuCasaContext.Instance);
             }
         }
        [HttpGet]
        public ActionResult Add(int id) {
            var member = _memberRepository.GetMemberBy(x => x.MemberId == id);
            var viewModel = _callLogRepository.GetCallLogsByMember(member);
            return View("Add", viewModel);
        }

        [HttpPost]
        public ActionResult Add(CallLogViewModel viewModel) {
            if (ModelState.IsValid) {
                var callLog = new CallLog();
                AutoMapper.Mapper.Map(viewModel, callLog);
                callLog.DateTime = DateTime.Now;
                if (!_callLogRepository.AddCallLog(callLog)) {
                    ModelState.AddModelError(string.Empty, "Couldn't persist course.");
                }
            }
            //maybe a success message in the layout
            return RedirectToAction("Index", "Home");
        }
    }
}